<template>
  <el-form ref="form" label-width="100px" :inline="false">
    <el-form-item label="SPU名称">
      <el-input v-model="SpuParams.spuName" placeholder="请输入你的SPU品牌" />
    </el-form-item>
    <el-form-item label="SPU品牌">
      <el-select v-model="SpuParams.tmId" placeholder="请选择" clearable filterable>
        <el-option v-for="(item, _index) in allTradeMark" :key="item.id" :label="item.tmName" :value="item.id" />
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input v-model="SpuParams.description" type="textarea" placeholder="请输入SPU品牌的描述" />
    </el-form-item>

    <el-form-item label="SPU图标">
      <el-upload v-model:file-list="imgList" action="/api/admin/product/fileUpload" list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handlerRemove" :before-upload="handlerUpload">
        <el-icon><Plus /></el-icon>
      </el-upload>
      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" width="100%" />
      </el-dialog>
    </el-form-item>
    <el-form-item label="SPU销售属性">
      <el-select v-model="saleAttrIdAndValueName" style="width: 200px" :placeholder="unSelectSaleAttr.length ? `还未选择${unSelectSaleAttr.length}个` : '无'" clearable filterable>
        <el-option v-for="(item, _index) in unSelectSaleAttr" :key="item.id" :label="item.name" :value="`${item.id}:${item.name}`" />
      </el-select>

      <el-button :disabled="saleAttrIdAndValueName ? false : true" type="primary" size="default" icon="Plus" @click="addSaleAttr">添加属性值</el-button>

      <el-table :data="saleAttr" style="margin-top: 10px" border stripe>
        <el-table-column type="index" width="80px" align="center" label="序号" />
        <el-table-column label="销售属性名字" width="120px" prop="saleAttrName" />
        <el-table-column label="销售属性值">
          <template #default="{ row }">
            <div class="tag-box">
              <el-tag v-for="(item, index) in row.spuSaleAttrValueList" :key="item.id" type="primary" closable @close="row.spuSaleAttrValueList.splice(index, 1)">
                {{ item.saleAttrValueName }}
              </el-tag>
              <el-input v-if="row.flag === true" v-model="row.saleAttrValue" placeholder="请您输入属性值" size="small" style="width: 100px" clearable @blur="toView(row)" />
              <el-button v-else type="success" size="small" icon="Plus" @click="toEdit(row)" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120px">
          <template #default="{ $index }">
            <el-button type="danger" size="default" icon="Delete" @click="saleAttr.splice($index, 1)" />
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button :loading="loading" type="primary" :disabled="saleAttr.length > 0 ? false : true" @click="save">保存</el-button>
      <el-button @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import type { SaleAttrValue, SpuData, TradeMark, AllTradeMark, SpuHasImg, SaleAttrResponseData, HasSaleAttrResponseData, SpuImg, SaleAttr, HasSaleAttr } from '@/api/product/spu/type';
import { reqAllTradeMark, reqSpuImageList, reqSpuHasSaleAttr, reqAllSaleAttr, reqAddOrUpdateSpu } from '@/api/product/spu/index';
import { computed, ref } from 'vue';
import { ElMessage } from 'element-plus';
let $emit = defineEmits(['changeScene']);
const cancel = () => {
  $emit('changeScene', { flag: 0, params: 'update' });
};

// 所有品牌
let allTradeMark = ref<TradeMark[]>([]);
// SPU图片列表
let imgList = ref<SpuImg[]>([]);
// SPU销售属性
let saleAttr = ref<SaleAttr[]>([]);
//所有销售属性
let allSaleAttr = ref<HasSaleAttr[]>([]);
//  SPU上传参数
let SpuParams = ref<SpuData>({
  category3Id: '',
  spuName: '',
  description: '',
  tmId: '',
  spuImageList: [],
  spuSaleAttrList: [],
});
//     let AllTradeMark = ref<TradeMark[]>([]);

//编辑SPU时初始化
const initHasSpuData = async (spu: SpuData) => {
  //清空数据
  clearLastData();
  SpuParams.value = spu;
  let result: AllTradeMark = await reqAllTradeMark();
  let result1: SpuHasImg = await reqSpuImageList(spu.id as number);
  let result2: SaleAttrResponseData = await reqSpuHasSaleAttr(spu.id as number);
  let result3: HasSaleAttrResponseData = await reqAllSaleAttr();

  //存储全部品牌的数据
  allTradeMark.value = result.data;
  //SPU对应图片
  imgList.value = result1.data.map((item) => {
    return {
      name: item.imgName,
      url: item.imgUrl,
    };
  });
  //存储已有的SPU的销售属性
  saleAttr.value = result2.data;
  //全部的销售属性
  allSaleAttr.value = result3.data;
};

// 图片预览
const dialogVisible = ref<boolean>(false);

// 存储图片地址
const dialogImageUrl = ref<string>('');

//照片墙预览
const handlePictureCardPreview = (file: any) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
};

//照片墙删除文件钩子
const handlerRemove = () => {};

//上传图片的钩子
const handlerUpload = (file: any) => {
  if (file.type === 'image/png' || file.type === 'image/jpeg' || file.type === 'image/gif') {
    if (file.size / 1024 / 1024 < 3) {
      return true;
    } else {
      ElMessage({
        type: 'error',
        message: '上传的文件大小不能超过3M',
      });
      return false;
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传的文件必须是PNG|JPG|GIF',
    });
    return false;
  }
};

//计算当前还未拥有的销售属性
let unSelectSaleAttr = computed(() => {
  let unSelectArr = allSaleAttr.value.filter((item) => {
    return saleAttr.value.every((item1) => {
      return item.name != item1.saleAttrName;
    });
  });
  return unSelectArr;
});

//将来收集还未选择的销售属性的ID和属性值的名字
let saleAttrIdAndValueName = ref('');

//添加销售属性的方法
const addSaleAttr = () => {
  const [baseSaleAttrId, saleAttrName] = saleAttrIdAndValueName.value.split(':');
  saleAttr.value;
  let newSaleAttr: SaleAttr = {
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: [],
  };
  saleAttr.value.push(newSaleAttr);
  saleAttrIdAndValueName.value = '';
};

//切换销售属性值编辑与添加
const toEdit = (row: SaleAttr) => {
  row.saleAttrValue = '';
  row.flag = true;
};

//销售属性值由编辑变查看
const toView = (row: SaleAttr) => {
  const { baseSaleAttrId, saleAttrValue } = row;
  //非空判断
  if ((saleAttrValue as string).trim() === '') {
    ElMessage({
      type: 'error',
      message: '销售属性值不能为空',
    });
    return;
  }
  let newSaleAttrValue: SaleAttrValue = {
    baseSaleAttrId,
    saleAttrValueName: saleAttrValue as string,
  };
  //判断销售属性值是否重复
  let repeat = row.spuSaleAttrValueList.find((item) => {
    return item.saleAttrValueName == saleAttrValue;
  });

  if (repeat) {
    ElMessage({
      type: 'error',
      message: '销售属性值不能重复',
    });
    return;
  }
  row.spuSaleAttrValueList.push(newSaleAttrValue);

  row.flag = false;
};

// 保存按钮节流阀
let loading = ref<boolean>(false);
//保存SPU
const save = async () => {
  if (loading.value) return;
  loading.value = true;
  // SpuParams.value.spuImageList;
  SpuParams.value.spuImageList = imgList.value.map((item: any) => {
    return {
      imgName: item.name,
      imgUrl: (item.response && item.response.data) || item.url,
    } as any;
  });

  SpuParams.value.spuSaleAttrList = saleAttr.value;
  let result = await reqAddOrUpdateSpu(SpuParams.value);
  if (result.code === 200) {
    ElMessage({
      type: 'success',
      message: SpuParams.value.id ? '更新成功' : '添加成功',
    });
    $emit('changeScene', { flag: 0, params: SpuParams.value.id ? 'update' : 'add' });
  } else {
    ElMessage({
      type: 'error',
      message: SpuParams.value.id ? '更新失败' : '添加失败',
    });
  }
  loading.value = false;
};

const clearLastData = () => {
  //清空数据
  Object.assign(SpuParams.value, {
    category3Id: '',
    spuName: '',
    description: '',
    tmId: '',
    spuImageList: [],
    spuSaleAttrList: [],
  });

  imgList.value = [];
  saleAttr.value = [];
  saleAttrIdAndValueName.value = '';
};

//添加一个新的SPU初始化请求方法
const initAddSpu = async (c3Id: number | string) => {
  //清空数据
  clearLastData();
  SpuParams.value.category3Id = c3Id;
  //获取全部品牌的数据
  let result: AllTradeMark = await reqAllTradeMark();
  let result1: HasSaleAttrResponseData = await reqAllSaleAttr();

  allTradeMark.value = result.data;
  allSaleAttr.value = result1.data;
};
//对外暴露父组件想拿到的方法
defineExpose({ initHasSpuData, initAddSpu });
</script>

<style lang="scss" scoped>
.tag-box {
  display: flex;
  gap: 10px;
}
</style>
